/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package eldermodone;

import java.awt.Color;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import org.python.core.PyException;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

/**
 *
 * @author KyleSweeney
 */
public class Console extends javax.swing.JFrame {

    PythonInterpreter pyInter;
    ConsoleOutputStream cos;
    ConsoleErrorStream ces;
    ArrayList<String> commands;
    int pointer;
    /**
     * Creates new form Console
     */
    public Console() {
        initComponents();
    }
    
    public Console(PythonInterpreter pyinter){
        initComponents();
        this.pyInter=pyinter;
        
        cos = new ConsoleOutputStream(Output);
        ces = new ConsoleErrorStream(Output);
//        PrintStream ps = new PrintStream(new ConsoleOutputStream(Output));
        pyInter.setOut(cos);
        pyInter.setErr(cos);
        commands = new ArrayList<String>();
        pointer = 0;
    }
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        input = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        Output = new javax.swing.JTextPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        input.setText(">>");
        input.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        input.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                inputActionPerformed(evt);
            }
        });
        input.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                inputKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                inputKeyTyped(evt);
            }
        });

        Output.setEditable(false);
        Output.setFont(new java.awt.Font("Lucida Console", 0, 11)); // NOI18N
        Output.setText("Elder Mod One Console");
        jScrollPane1.setViewportView(Output);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(input, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
            .addComponent(jScrollPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(input, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void inputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inputActionPerformed
        
    }//GEN-LAST:event_inputActionPerformed

    private void inputKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_inputKeyPressed
        
        if(evt.getKeyChar() == '\n'){
            String text = input.getText().substring(2);
            Output.setText(Output.getText()+"\n>>"+text+"\n");
            try{
                pyInter.exec(text);
            }catch(PyException e){
                try {
                    cos.writeError(e);
                } catch (IOException ex) {
                    //yshould never happen.....
                    Logger.getLogger(Console.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            input.setText(">>");
            this.commands.add(text);
            this.pointer = commands.size();
        }
        
        if(evt.getKeyCode() == KeyEvent.VK_UP){
            if(pointer <=0 ){
                input.setText(">>"+commands.get(0));
                return;
            }
            input.setText(">>"+commands.get(pointer--));
        }else if(evt.getKeyCode() == KeyEvent.VK_DOWN){
            if(pointer <= commands.size()-1 ){
                input.setText(">>"+commands.get(commands.size()-1));
                return;
            }
            input.setText(">>"+commands.get(pointer++));
        }
        
        if(evt.getKeyChar() == 127 && input.getText().equals(">>")){
            return;
        }
    }//GEN-LAST:event_inputKeyPressed

    private void inputKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_inputKeyTyped

    }//GEN-LAST:event_inputKeyTyped

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Console.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Console.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Console.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Console.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Console().setVisible(true);
            }
        });
    }
    
    
    private class ConsoleOutputStream extends OutputStream{

        JTextPane consoleout;
        
        public ConsoleOutputStream(JTextPane jta){
            consoleout = jta;
        }
        public void writeError(PyException e) throws IOException{
            char[] msg = e.toString().toCharArray();
            for(char c : msg){
                this.write(c);
            }
        }
        
        @Override
        public void write(int b) throws IOException {
            char c = (char)b;
            StyleContext sc = StyleContext.getDefaultStyleContext();
            AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.black);

            aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
            aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);

            consoleout.setText(consoleout.getText()+""+c);
            int len = consoleout.getDocument().getLength()-1;
            consoleout.setCaretPosition(len);
            consoleout.setCharacterAttributes(aset, false);
        }
        
    }
    
    private class ConsoleErrorStream extends OutputStream{

        JTextPane consoleout;
        
        public ConsoleErrorStream(JTextPane jta){
            consoleout = jta;
        }
        
        public void writeError(PyException e) throws IOException{
            char[] msg = e.toString().toCharArray();
            for(char c : msg){
                this.write(c);
            }
        }
        
        @Override
        public void write(int b) throws IOException {
            char c = (char)b;
            StyleContext sc = StyleContext.getDefaultStyleContext();
            AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.red);

            aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
            aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);

            consoleout.setText(consoleout.getText()+""+c);
            int len = consoleout.getDocument().getLength()-1;
            consoleout.setCaretPosition(len);
            consoleout.setCharacterAttributes(aset, false);
            consoleout.replaceSelection(""+c);
        }
        
    }
    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextPane Output;
    private javax.swing.JTextField input;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
